package com.haibo.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author : 刘海波
 * @Date: 2025-09-08 21:24
 * @Description:
 */
@Configuration
@MapperScan(
        basePackages = "com.haibo.business.three.mapper",
        sqlSessionFactoryRef = "sqlSessionFactory3",
        sqlSessionTemplateRef = "sqlSessionTemplate3"
)
public class DataSource3Config {

    public static final String DS3_TYPE_ALIASES_PACKAGE = "com.haibo.business.three.entity.model";

    /**
     * 数据源3
     * @return
     */
    @Bean(name = "ds3")
    @ConfigurationProperties(prefix = "spring.datasource.ds3")
    public DataSource ds3() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 会话工厂3
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactory3")
    public SqlSessionFactory sqlSessionFactory3(@Qualifier("ds3") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 配置MySQL的Mapper路径
        sessionFactory.setTypeAliasesPackage(DS3_TYPE_ALIASES_PACKAGE);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactory.setConfiguration(configuration);

        return sessionFactory.getObject();
    }


    /**
     * 事务管理器3
     * @param dataSource
     * @return
     */
    @Bean(name = "transactionManager3")
    public DataSourceTransactionManager transactionManager3(@Qualifier("ds3") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * 会话模板3
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "sqlSessionTemplate3")
    public SqlSessionTemplate sqlSessionTemplate3(@Qualifier("sqlSessionFactory3") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
